<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="80px">
            <el-form-item label="订单号" prop="orderNo">
                <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="程序员" prop="programmerName">
                <el-input v-model="queryParams.programmerName" placeholder="请输入程序员姓名" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="订单任务类型" prop="orderTaskName">
                <el-select v-model="queryParams.orderTaskName" placeholder="请选择任务类型" clearable>
                    <el-option v-for="task in taskTypeOptions" :key="task.value" :label="task.label"
                        :value="task.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="派单状态" prop="state">
                <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
                    <el-option v-for="dict in stateOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button type="primary" size="mini" @click="registration">技术注册</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-dropdown @command="handleSort" trigger="click">
                    <el-button size="mini">
                        竞价排序<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="bidding_amount.asc">金额升序</el-dropdown-item>
                        <el-dropdown-item command="bidding_amount.desc">金额降序</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-form-item>
        </el-form>

        <!-- <el-row :gutter="10" class="mb8"> -->
        <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['dashboard:preempt:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dashboard:preempt:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dashboard:preempt:remove']">删除</el-button>
      </el-col> -->
        <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['dashboard:preempt:export']">导出</el-button>
      </el-col> -->
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
        <!-- </el-row> -->

        <el-table v-loading="loading" :data="preemptList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="订单号" align="center" prop="orderNo" width="180" :show-overflow-tooltip="true" />
            <el-table-column label="订单标题" align="center" prop="orderTitle" width="200" :show-overflow-tooltip="true" />
            <el-table-column label="订单任务类型" align="center" prop="orderTaskName" width="200"
                :show-overflow-tooltip="true" />
            <!-- <el-table-column label="简介" align="center" prop="introduce" width="250" :show-overflow-tooltip="true" /> -->
            <el-table-column label="客户" align="center" prop="customerName" />
            <el-table-column label="程序类型" align="center" prop="techType" :show-overflow-tooltip="true" />
            <el-table-column label="是否加急" align="center" prop="isUrgent">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.isUrgent === '1' ? 'danger' : 'info'" size="small">{{
                        selectDictLabel(isUrgentOptions, scope.row.isUrgent) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="订单总价" align="center" prop="rewardAmount">
                <template slot-scope="scope">
                    <span>¥{{ (scope.row.rewardAmount || 0) + (scope.row.raiseAmount || 0) }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="技术状态" align="center" prop="workStatus">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(workStatusOptions, scope.row.workStatus) }}</span>
        </template>
      </el-table-column> -->
            <el-table-column label="订单状态" align="center" prop="orderStatus">
                <template slot-scope="scope">
                    <el-tag :type="getStatusTag(scope.row.orderStatus)">{{ selectDictLabel(orderStatusOptions,
                        scope.row.orderStatus) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="收款状态" align="center" prop="orderStatusAmount">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.orderStatusAmount === '4' ? 'danger' : 'info'" size="small">
                        {{ selectDictLabel(orderStatusAmountOptions, scope.row.orderStatusAmount) }}
                    </el-tag>
                </template>
            </el-table-column>
            <!-- <el-table-column label="技能要求" align="center" prop="requiredSkillLevelId" width="120"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(skillLevelOptions, scope.row.requiredSkillLevelId) }}</span>
        </template>
      </el-table-column> -->
            <el-table-column label="信用分" align="center" prop="requiredCreditScore" />
            <!-- <el-table-column label="售前" align="center" prop="preSalesName" />
      <el-table-column label="售中" align="center" prop="inSaleName" />
      <el-table-column label="售后" align="center" prop="afterSaleName" /> -->
            <el-table-column label="包单价" align="center" prop="biddingAmount">
                <template slot-scope="scope">
                    <span>¥{{ scope.row.biddingAmount || 0 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="派单状态" align="center" prop="state">
                <template slot-scope="scope">
                    <el-tag :type="getStateTag(scope.row.state)">{{ selectDictLabel(stateOptions, scope.row.state)
                        }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="外部程序员" align="center" prop="programmerName" />
            <el-table-column label="推荐状态" align="center" prop="isRecommended" width="100">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.isRecommended" type="primary" 
                            style="background-color: #409EFF; border-color: #409EFF; color: white;">
                        <i class="el-icon-star-on"></i> 推荐
                    </el-tag>
                    <span v-else style="color: #909399;">-</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="备注" align="center" prop="remark" width="200" :show-overflow-tooltip="true" /> -->
            <el-table-column label="截止时间" align="center" prop="estimatedEndTime" width="160">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.estimatedEndTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handleDispatch(scope.row)"
                        v-hasPermi="['dashboard:preempt:edit']" :disabled="scope.row.state !== '0'">派单</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改外部技术抢单对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="订单号" prop="gradOrdersId">
                    <el-input v-model="form.gradOrdersId" placeholder="请输入订单号" :disabled="true" />
                </el-form-item>
                <el-form-item label="包单价" prop="biddingAmount">
                    <el-input v-model="form.biddingAmount" placeholder="请输入包单价" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 派单对话框 -->
        <el-dialog :title="dispatchTitle" :visible.sync="openDispatch" width="500px" append-to-body>
            <el-form ref="dispatchForm" :model="dispatchForm" :rules="dispatchRules" label-width="80px">
                <el-form-item label="包单价" prop="biddingAmount">
                    <el-input v-model="dispatchForm.biddingAmount" placeholder="请输入包单价" />
                </el-form-item>
                <el-form-item label="截止时间" prop="estimatedEndTime">
                    <el-date-picker clearable v-model="dispatchForm.estimatedEndTime" type="date"
                        value-format="yyyy-MM-dd" placeholder="请选择截止时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="选择售后" prop="afterSaleId">
                    <el-select v-model="dispatchForm.afterSaleId" placeholder="请选择售后人员" clearable filterable>
                        <el-option
                            v-for="user in afterSaleOptions"
                            :key="user.userId"
                            :label="user.nickName || user.userName"
                            :value="user.userId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitDispatchForm">确 定</el-button>
                <el-button @click="cancelDispatch">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 技术注册对话框 -->
        <el-dialog title="技术注册" :visible.sync="openRegistration" width="500px" append-to-body>
            <el-form ref="registrationForm" :model="registrationForm" :rules="registrationRules" label-width="100px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="registrationForm.userName" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="registrationForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="支付宝姓名" prop="alipayName">
                    <el-input v-model="registrationForm.alipayName" placeholder="请输入支付宝姓名" />
                </el-form-item>
                <el-form-item label="支付宝账号" prop="alipayAccount">
                    <el-input v-model="registrationForm.alipayAccount" placeholder="请输入支付宝账号" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitRegistrationForm">确 定</el-button>
                <el-button @click="cancelRegistration">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { listPreempt, getPreempt, delPreempt, addPreempt, updatePreempt, dispatchOrder } from "@/api/dashboard/preempt"
import { listAllSkillLevels } from "@/api/dashboard/orders"
import { listType } from "@/api/dashboard/type"
import { registration, listUsersByRoleName } from "@/api/system/user"

export default {
    name: "Preempt",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 外部技术抢单表格数据
            preemptList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            taskTypeOptions: [],
            // 售后选项
            afterSaleOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderNo: null,
                programmerName: null,
                orderTaskName: null,
                state: '0' // 默认值：未中单
            },
            // 表单参数
            form: {},
            // 用户导入参数
            dispatchForm: {
                id: null,
                estimatedEndTime: null,
                biddingAmount: null,
                afterSaleId: null,
                gradOrdersId: null,
            },
            // 弹出层标题
            dispatchTitle: "",
            // 是否显示弹出层
            openDispatch: false,
            // 表单校验
            rules: {
                biddingAmount: [
                    { required: true, message: "包单价不能为空", trigger: "blur" }
                ],
            },
            dispatchRules: {
                biddingAmount: [
                    { required: true, message: "包单价不能为空", trigger: "blur" }
                ],
                estimatedEndTime: [
                    { required: true, message: "截止时间不能为空", trigger: "blur" }
                ]
            },
            // 字典数据
            orderStatusOptions: [
                { label: '待抢单', value: '0' },
                { label: '重包单', value: '1' },
                { label: '进行中', value: '2' },
                { label: '未过售后期', value: '6' },
                { label: '已完成', value: '5' },
                { label: '服务费', value: '7' },
                { label: '已退单', value: '4' }
                // { label: '外部技术', value: '3' },
            ],
            orderStatusAmountOptions: [
                { label: '定金', value: '0' },
                { label: '首款', value: '1' },
                { label: '中期款', value: '2' },
                { label: '尾款', value: '3' },
                { label: '退款', value: '4' }
            ],
            isUrgentOptions: [
                { label: '加急', value: '1' },
                { label: '不加急', value: '0' }
            ],
            skillLevelOptions: [],
            stateOptions: [
                { label: '未派单', value: '0' },
                { label: '未中单', value: '1' },
                { label: '中单', value: '2' },
                { label: '已退单', value: '3' }
            ],
            workStatusOptions: [
                { label: '内部技术', value: '0' },
                { label: '外部技术', value: '1' }
            ],
            // 技术注册相关
            openRegistration: false,
            registrationForm: {
                userName: null,
                phone: null,
                alipayName: null,
                alipayAccount: null,
            },
            registrationRules: {
                userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                alipayName: [{ required: true, message: '支付宝姓名不能为空', trigger: 'blur' }],
                alipayAccount: [{ required: true, message: '支付宝账号不能为空', trigger: 'blur' }],
            },
        }
    },
    created() {
        this.getList()
        this.getSkillLevels()
        this.getTaskTypes()
        this.getAfterSaleUsers()
    },
    methods: {
        /** 查询外部技术抢单列表 */
        getList() {
            this.loading = true
            listPreempt(this.queryParams).then(response => {
                this.preemptList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        /** 查询技术等级列表 */
        getSkillLevels() {
            listAllSkillLevels().then(response => {
                this.skillLevelOptions = response.data.map(item => ({
                    value: item.id,
                    label: `${item.levelCode} - ${item.levelName}`
                }));
            });
        },
        /** 查询任务类型列表 */
        getTaskTypes() {
            listType({ pageNum: 1, pageSize: 999 }).then(response => {
                this.taskTypeOptions = response.rows.map(item => ({
                    value: item.orderTaskName,
                    label: item.orderTaskName
                }));
            });
        },
        /** 获取售后用户列表 */
        getAfterSaleUsers() {
            listUsersByRoleName('售后').then(response => {
                this.afterSaleOptions = response.data || [];
                console.log('售后用户列表:', this.afterSaleOptions);
            }).catch(error => {
                console.error('获取售后用户列表失败:', error);
            });
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        cancelDispatch() {
            this.openDispatch = false;
            this.resetDispatchForm();
        },
        cancelRegistration() {
            this.openRegistration = false;
            this.resetRegistrationForm();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                gradOrdersId: null,
                programmerName: null,
                programmerId: null,
                biddingAmount: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm("form")
        },
        resetDispatchForm() {
            this.dispatchForm = {
                id: null,
                estimatedEndTime: null,
                biddingAmount: null,
                afterSaleId: null,
                gradOrdersId: null,
            };
            this.resetForm("dispatchForm");
        },
        resetRegistrationForm() {
            this.registrationForm = {
                userName: null,
                name: null,
                phone: null,
                alipayName: null,
                alipayAccount: null,
            };
            this.resetForm("registrationForm");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.queryParams.params = {}; // 清空排序
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm")
            this.queryParams.params = {};
            this.queryParams.orderTaskName = null;
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = "添加外部技术抢单"
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getPreempt(id).then(response => {
                this.form = response.data
                this.open = true
                this.title = "修改我的竞价"
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updatePreempt(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功")
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addPreempt(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功")
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除外部技术抢单编号为"' + ids + '"的数据项？').then(function () {
                return delPreempt(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => { })
        },
        /** 派单按钮操作 */
        handleDispatch(row) {
            this.resetDispatchForm();
            this.dispatchForm.id = row.id;
            this.dispatchForm.gradOrdersId = row.gradOrdersId; // 设置订单ID
            this.dispatchForm.biddingAmount = row.biddingAmount; // 初始化包单价
            this.dispatchForm.estimatedEndTime = row.estimatedEndTime; // 初始化截止时间
            this.dispatchTitle = "派单给 " + row.programmerName;
            this.openDispatch = true;
        },
        /** 提交派单表单 */
        submitDispatchForm() {
            this.$refs["dispatchForm"].validate(valid => {
                if (valid) {
                    // 构造派单数据，将afterSaleId映射到dispatchAfterSaleId
                    const dispatchData = {
                        id: this.dispatchForm.id,
                        estimatedEndTime: this.dispatchForm.estimatedEndTime,
                        biddingAmount: this.dispatchForm.biddingAmount,
                        dispatchAfterSaleId: this.dispatchForm.afterSaleId // 映射字段名
                    };
                    console.log("Dispatching data:", dispatchData);
                    this.$modal.confirm('确认要派单给该程序员吗？').then(() => {
                        return dispatchOrder(dispatchData);
                    }).then(() => {
                        this.$modal.msgSuccess("派单成功");
                        this.openDispatch = false;
                        this.getList();
                    }).catch(() => { });
                }
            });
        },
        /** 技术注册按钮操作 */
        registration() {
            this.openRegistration = true;
        },
        /** 提交技术注册表单 */
        submitRegistrationForm() {
            this.$refs["registrationForm"].validate(valid => {
                if (valid) {
                    // 构造注册数据，映射到SysUser字段
                    const registrationData = {
                        userName: this.registrationForm.userName,       // 用户名 -> userName        
                        phonenumber: this.registrationForm.phone,       // 手机号 -> phonenumber
                        alipayRealName: this.registrationForm.alipayName, // 支付宝姓名 -> alipayRealName
                        alipayNumber: this.registrationForm.alipayAccount // 支付宝账号 -> alipayNumber
                    };

                    console.log("Registration data:", registrationData);
                    this.$modal.confirm('确认要提交技术注册吗？').then(() => {
                        registration(registrationData).then(response => {
                            this.$modal.msgSuccess("技术注册成功");
                            this.openRegistration = false;
                            this.resetRegistrationForm();
                        }).catch(error => {
                            this.$modal.msgError("技术注册失败：" + (error.msg || "未知错误"));
                        });
                    }).catch(() => { });
                }
            });
        },
        /** 排序操作 */
        handleSort(command) {
            const [column, order] = command.split('.');
            this.queryParams.params = {
                orderByColumn: column,
                sortOrder: order
            };
            this.getList();
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('dashboard/preempt/export', {
                ...this.queryParams
            }, `preempt_${new Date().getTime()}.xlsx`)
        },
        /** 转换字典标签 */
        selectDictLabel(datas, value) {
            if (value === undefined || value === null || value === '') {
                return "";
            }
            const actions = [];
            Object.keys(datas).map((key) => {
                if (datas[key].value == ('' + value)) {
                    actions.push(datas[key].label);
                    return false;
                }
            })
            return actions.join('');
        },
        getStatusTag(status) {
            const statusOptions = {
                '0': 'info',
                '1': 'success',
                '2': 'warning',
                '3': 'danger',
                '4': 'info',
                '5': 'success',
                '6': 'waring',
                '7': 'danger'
            };
            return statusOptions[status] || 'info';
        },
        getStateTag(state) {
            const stateColors = {
                '0': 'info',
                '1': 'warning',
                '2': 'success',
                '3': 'danger'
            };
            return stateColors[state] || 'info';
        },
    }
}
</script>
